package com.wrupple.muba.desktop.client.bootstrap.state.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.wrupple.muba.common.domain.RawSlice;
import com.wrupple.muba.common.shared.StateTransition;
import com.wrupple.muba.desktop.client.bootstrap.state.LoadDesktopModules;
import com.wrupple.muba.desktop.client.events.DesktopModuleInitializedEvent;
import com.wrupple.muba.desktop.client.module.DesktopModuleController;
import com.wrupple.muba.desktop.client.module.ModuleController;
import com.wrupple.muba.desktop.client.module.ModuleController.ModuleConfiguration;
import com.wrupple.muba.desktop.domain.DesktopDescriptor;
import com.wrupple.muba.desktop.domain.DesktopLoadingStateHolder;

public class LoadDesktopModulesImpl implements LoadDesktopModules {

	private Map<String, ModuleController<? extends ModuleConfiguration>> modules;
	
	
	DesktopModuleController desktopModuleController;
	
	@Inject
	public LoadDesktopModulesImpl(DesktopModuleController desktopModuleController) {
		super();
		this.desktopModuleController = desktopModuleController;
	}

	@Override
	public void start(DesktopLoadingStateHolder parameter, StateTransition<DesktopLoadingStateHolder> onDone,EventBus eventBus) {
		DesktopDescriptor desktop = parameter.getDesktopDescriptor();
		Collection<RawSlice> raws = desktop.getRawSlices();
		ModuleController module;
		String moduleName ;
		Map<String, Activity> activityMap = new HashMap<String, Activity>();
		for(RawSlice raw : raws){
			if(raw.getSlice()!=null){
				moduleName  = raw.getDefaultName();
				module = modules.get(moduleName);
				if(module!=null){
					module.setConfiguration(raw.getSlice().getConfigurationObject());
					module.initialize();
					activityMap.putAll(module.getActivities());
					eventBus.fireEvent(new DesktopModuleInitializedEvent(module,raw.getDefaultName()));
				}
			}
		}
		parameter.registerAll(activityMap);
		desktopModuleController.setConfiguration(parameter.getDesktopDescriptor());
		parameter.registerAll(desktopModuleController.getActivities());
		
		onDone.setResultAndFinish(parameter);
	}

	@Override
	public void setDesktopModules(Map<String, ModuleController<? extends ModuleConfiguration>> assignedModules) {
		this.modules = assignedModules;
	}

}
